﻿using System;
using System.Web;
using System.Web.Security;
using ITS.Core.Domain.Users;
using ITS.Core.ViewModel.Users;
using ITS.Infrastructure.Constants;

namespace ITS.Infrastructure.Helpers
{
    public class AuthenticationHelper
    {
        public static void AdminAccountLogin(User user, string name, string id, bool rememberMe)
        {
            SessionHelper.SetSession<object>(SessionNames.UserSessionModel, UserSessionModel.FromUser(user));

            if (rememberMe)
            {
                int cookieExpireDay = 14;
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                1,
                                name,
                                DateTime.Now,
                                DateTime.Now.AddDays(cookieExpireDay),
                                true,
                                id);
                string hashedTicket = FormsAuthentication.Encrypt(ticket);

                HttpCookie cookie = new HttpCookie(ConstantsHelper.CookieName_User.UserCookie, hashedTicket);
                cookie.Expires = DateTime.Now.AddDays(cookieExpireDay);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            else
            {
                HttpContext.Current.Response.Cookies[ConstantsHelper.CookieName_User.UserCookie].Expires = DateTime.Today.AddDays(-1);
            }
        }
        public static void AdminAccountLogout()
        {
            SessionHelper.ClearSession(SessionNames.UserSessionModel);
            HttpContext.Current.Response.Cookies[ConstantsHelper.CookieName_User.UserCookie].Expires = DateTime.Today.AddDays(-1);
        }

        public static string LoggedUserDisplayName
        {
            get
            {
                UserSessionModel userSessionMode = SessionHelper.GetSession<object>(SessionNames.UserSessionModel) as UserSessionModel;
                if (userSessionMode == null)
                    return String.Empty;
                else if (!String.IsNullOrEmpty(userSessionMode.DisplayName))
                    return userSessionMode.DisplayName;
                else
                    return userSessionMode.Username;
            }
        }
    }
}
